package com.example.demo.Controller;

import com.example.demo.Common.Constants;
import com.example.demo.Common.OException;
import com.example.demo.Common.ServiceResultEnum;
import com.example.demo.Config.Annotation.TokenToUser;
import com.example.demo.Entity.Customer;
import com.example.demo.Entity.Product;
import com.example.demo.Param.ProductDetailParam;
import com.example.demo.Param.UserParam;
import com.example.demo.Service.ProductService;
import com.example.demo.Service.UserService;
import com.example.demo.Util.*;
import com.example.demo.VO.ProductDetailVO;
import com.example.demo.VO.SearchProductVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
public class ProductController {

    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Resource
    private ProductService productService;

    @Resource
    private UserService userService;

    @GetMapping("/search")
    @ApiOperation(value = "商品搜索接口", notes = "根据关键字进行搜索")
    public Result<PageResult<List<SearchProductVO>>> search(@RequestParam(required = false) @ApiParam(value = "搜索关键字") String keyword,
                                                            @RequestParam(required = false) @ApiParam(value = "orderBy") String orderBy,
                                                            @RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
                                                            @RequestBody @Valid UserParam userParam) {

        Customer customer = userService.getCDetail(userParam.getTelphone());
        logger.info("goods search api,keyword={},goodsCategoryId={},orderBy={},pageNumber={},userId={}", keyword, orderBy, pageNumber, customer.getId());

        Map params = new HashMap(4);
        //两个搜索参数都为空，直接返回异常
        if (StringUtils.isEmpty(keyword)) {
            OException.fail("非法的搜索参数");
        }
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        params.put("page", pageNumber);
        params.put("limit", Constants.PRODUCTS_SEARCH_PAGE_LIMIT);
        //对keyword做过滤 去掉空格
        if (!StringUtils.isEmpty(keyword)) {
            params.put("keyword", keyword);
        }
        if (!StringUtils.isEmpty(orderBy)) {
            params.put("orderBy", orderBy);
        }
        //搜索上架状态下的商品
        params.put("goodsSellStatus", Constants.SELL_STATUS_UP);
        //封装商品数据
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(productService.searchProducts(pageUtil));
    }

    /*@GetMapping("/products/detail/{productId}")
    @ApiOperation(value = "商品详情接口", notes = "传参为商品id")
    public Result<ProductDetailVO> productDetail(@ApiParam(value = "商品id") @PathVariable("prpductId") Long goodsId, @TokenToMallUser MallUser loginMallUser) {
        logger.info("goods detail api,goodsId={},userId={}", goodsId, loginMallUser.getUserId());
        if (goodsId < 1) {
            return ResultGenerator.genFailResult("参数异常");
        }
        Goods goods = productService.getGoodsById(goodsId);
        if (goods == null) {
            return ResultGenerator.genFailResult("参数异常");
        }
        if (Constants.SELL_STATUS_UP != goods.getGoodsSellStatus()) {
            OException.fail(ServiceResultEnum.GOODS_PUT_DOWN.getResult());
        }
        ProductDetailVO productDetailVO = new ProductDetailVO();
        BeanUtil.copyProperties(goods, productDetailVO);
        productDetailVO.setGoodsCarouselList(goods.getGoodsCarousel().split(","));
        return ResultGenerator.genSuccessResult(productDetailVO);
    }*/

    @PostMapping("/products/details")
    @ApiOperation(value = "商品详情接口", notes = "传参为商品id")
    //public Result<ProductDetailVO> productDetail(@RequestBody ProductDetailParam productDetailParam, @RequestBody @Valid UserParam userParam) {
    public Result<ProductDetailVO> productDetail(@RequestBody ProductDetailParam productDetailParam) {
        //log.info("mmm");
        log.info(String.valueOf(productDetailParam.getProductId()), productDetailParam.getTelphone());
        //log.info(userParam.getTelphone());
        Long productId = productDetailParam.getProductId();
        logger.info("product detail api,productId={},userTel={}", productId, productDetailParam.getTelphone());
        if (productId < 1) {
            return ResultGenerator.genFailResult("参数异常");
        }
        Product product = productService.getProductById(productId);
        if (product == null) {
            return ResultGenerator.genFailResult("参数异常");
        }
        /*if (Constants.SELL_STATUS_UP != product.getGoodsSellStatus()) {
            OException.fail(ServiceResultEnum.GOODS_PUT_DOWN.getResult());
        }*/
        ProductDetailVO productDetailVO = new ProductDetailVO();
        productDetailVO.setProductId(productId);
        productDetailVO.setProductName(product.getProductname());
        productDetailVO.setProductPrice(product.getProductprice());
        productDetailVO.setProductIntro(product.getProductinfo());
        productDetailVO.setProductCoverImg(product.getProductCoverImg());

        //BeanUtil.copyProperties(product, productDetailVO);
        productDetailVO.setProductCarouselList(product.getProductCarousel().split(","));
        return ResultGenerator.genSuccessResult(productDetailVO);
    }
}
